package com.xgk.boot.framework.redis.core;

import com.xgk.boot.framework.common.constant.ErrorCodeConstants;
import com.xgk.boot.framework.common.exception.util.ServiceExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisLockManager {

    private RedissonClient redissonClient;
    public RedisLockManager(RedissonClient redissonClient){
        this.redissonClient =redissonClient;
    }

    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public boolean tryLock(String lockName,long waitTime, long leaseTime) throws InterruptedException {
        return tryLock(lockName, waitTime, leaseTime, TimeUnit.SECONDS);
    }

    public boolean tryLock(String lockName, long waitTime, long leaseTime, TimeUnit timeUnit) throws InterruptedException {
        long start = System.currentTimeMillis();
        boolean locked = redissonClient.getLock(lockName).tryLock(waitTime, leaseTime, timeUnit);
        long end = System.currentTimeMillis();
//        if(!locked){
//            log.error("获取订单创建锁失败,{}", lockName);
//            throw ServiceExceptionUtil.exception(ErrorCodeConstants.REQUEST_EXCEPTION, "获取订单创建锁失败,"+lockName);
//        }
        if (end - start > 1000) {
            log.warn("获取订单创建锁等待时间较长: {}ms, lockName: {}", end - start,lockName);
        }
        return locked;
    }

    public void unlock(String lockName) {
        try {
            RLock lock = redissonClient.getLock(lockName);
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        } catch (Exception e) {
            log.error("释放锁失败, lockName: {}", lockName, e);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_EXCEPTION, "释放锁失败," + lockName);
        }
    }
}
